import { createApp, h } from 'vue';
import { ElImageViewer } from 'element-plus';

interface PreviewOptions {
	initialIndex?: number;
	zIndex?: number;
	hideOnClickModal?: boolean;
}

export function createImagePreview(images: string[], options: PreviewOptions = {}) {
	if (!images.length) return;

	const viewerContainer = document.createElement('div');
	document.body.appendChild(viewerContainer);

	const viewerApp = createApp({
		setup() {
			const show = ref(true);
			const initialIndex = ref(options.initialIndex || 0);

			// 创建计数器和指示器容器
			const indicatorContainer = document.createElement('div');
			indicatorContainer.style.cssText = `
        position: fixed;
        bottom: 70px;
        left: 50%;
        transform: translateX(-50%);
        z-index: ${(options.zIndex || 3000) + 100};
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 12px;
      `;
			document.body.appendChild(indicatorContainer);

			// 切换图片的函数
			const switchImage = (index: number) => {
				initialIndex.value = index;
				updateIndicator(index);
			};

			const onClose = () => {
				show.value = false;
				setTimeout(() => {
					viewerApp.unmount();
					document.body.removeChild(viewerContainer);
					document.body.removeChild(indicatorContainer);
				}, 200);
			};

			// 更新指示器
			const updateIndicator = (index: number) => {
				const counter = document.createElement('div');
				counter.style.cssText = `
          color: #fff;
          font-size: 14px;
          padding: 4px 12px;
          background: rgba(0, 0, 0, 0.5);
          border-radius: 12px;
        `;
				counter.textContent = `${index + 1} / ${images.length}`;

				const dots = document.createElement('div');
				dots.style.cssText = 'display: flex; gap: 8px;';

				images.forEach((_, idx) => {
					const dot = document.createElement('div');
					dot.style.cssText = `
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: ${idx === index ? '#fff' : 'rgba(255, 255, 255, 0.5)'};
            transition: all 0.3s ease;
            cursor: pointer;
          `;
					dot.onclick = () => switchImage(idx);
					dots.appendChild(dot);
				});

				indicatorContainer.innerHTML = '';
				indicatorContainer.appendChild(counter);
				indicatorContainer.appendChild(dots);
			};

			// 初始化指示器
			onMounted(() => {
				updateIndicator(initialIndex.value);
			});

			return () =>
				show.value
					? h(ElImageViewer, {
							urlList: images,
							initialIndex: initialIndex.value,
							onClose,
							zIndex: options.zIndex || 3000,
							hideOnClickModal: options.hideOnClickModal ?? false,
							teleported: true,
							onSwitch: (index) => {
								switchImage(index);
							},
						})
					: null;
		},
	});

	viewerApp.mount(viewerContainer);
}
